/*
The MIT License

Copyright (c) 2010 Michael Webb

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in
all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
THE SOFTWARE.
 */
//EL
(function() {
	CA.Interfaces.Create("IBroadcastHandlerComponent", [
			"InitializeComponent", "SetComponentID", "GetComponentID",
			"OnBroadcast" ]);
	var events = {};
	var targets = {};
	var components_to_groups = {};
	var groups = {};
	var _NULL = "__CA_SERVICES__NULL__";
	function EventIndex(items, fn, scope) {
		var index = -1;
		for ( var i = 0; i < items.length; i++) {
			var item = items[i];
			if (item["fn"] == fn && item["scope"] == scope) {
				index = i;
				break;
			}
		}
		return index;
	}
	/**
	 * @class
	 * @static
	 */
	CA.ComponentCommunications = {
		/**
		 * Returns a value that represents an "Any" match for components
		 * @function Any
		 * @return {string} a the value
		 */
		Any : function() {
			return _NULL;
		},
		_getTarget : function(target) {
			var targetType = typeof (target);
			if (targetType === "undefined" || target === null) {
				return _NULL;
			} else if (targetType == "string") {
				return target;
			} else if (CA.Interfaces.Check(target, "IComponent")) {
				return target["GetComponentID"]();
			}
			throw new Error("Cannot handle type of object passed.");
		},
		/**
		 * A method that sends a message (invokes a function) on a component if
		 * it exists.  Additional arguments are passed on as part of the message
		 * @function SendMessage
		 * @param {string} component_id The component id
		 * @param {string} message The message (function name) of the target component
		 * @return {boolean} indicating if the message was successfully sent
		 */
		SendMessage : function(component_id, message) {
			var cmp = CA.Components.Get(component_id);
			if (cmp) {
				if (typeof (cmp[message]) === "function") {
					var args = Array.prototype.slice.call(arguments,2);
					if (cmp[message]) {
						cmp[message].apply(cmp, args);
						return true;
					}
				}
			}
			return false;
		},
		/**
		 * Connect to an event on a target
		 * @function Connect
		 * @param {string} target The target (component id) to connect to
		 * @param {string} event The event being listened for
		 * @param {Function} fn The handler for the event
		 * @param {Object} scope The scope to invoke the handler with
		 */
		Connect : function(target, event, fn, scope) {
			target = this._getTarget(target);
			if (typeof (scope) === "undefined") {
				scope = null;
			}
			eventEntries = CA.NameSpace(event, events);
			if (typeof (eventEntries[target]) === "undefined") {
				eventEntries[target] = [];
			}
			var entries = eventEntries[target];
			if (EventIndex(entries, fn, scope) == -1) {
				entries.push( {
					"fn" : fn,
					"scope" : scope,
					"target" : target
				});
			}
		},
		/**
		 * Disconnect from an event on a target
		 * @function Disconnect
		 * @param {string} target The target (component id) to disconnect from
		 * @param {string} event The event being listened for
		 * @param {Function} fn The handler for the event
		 * @param {Object} scope The scope to invoke the handler with
		 */
		Disconnect : function(target, event, fn, scope) {
			target = this._getTarget(target);
			eventEntries = CA.NameSpace(event, events);
			if (typeof (eventEntries[target]) === "undefined") {
				return;
			}
			if (typeof (scope) === "undefined") {
				scope = null;
			}
			var entries = eventEntries[target];
			var index = EventIndex(entries, fn, scope);
			if (index != -1) {
				entries.splice(index, 1);
			}
			if (entries.length === 0) {
				delete eventEntries[target];
			}
		},
		/**
		 * A method that fires an event on a component additional arguments 
		 * are passed on as part of the event
		 * @function FireEvent
		 * @param {string} target The target (component id)
		 * @param {string} event The event to throw 
		 */
		FireEvent : function(target, event) {
			target = this._getTarget(target);
			targets = [ target ];
			if (target !== _NULL) {
				targets.push(_NULL);
			}
			eventEntries = CA.NameSpace(event, events);
			var args = Array.prototype.slice.call(arguments,2);
			for ( var k = 0; k < targets.length; k++) {
				target = targets[k];
				if (typeof (eventEntries[target]) === "undefined") {
					continue;
				}
				var listeners = eventEntries[target].slice(0);
				for ( var j = 0; j < listeners.length; j++) {
					var entry = listeners[j];
					try {
						entry["fn"].apply(entry["scope"], args);
					} catch (e) {

					}
				}
			}
		},
		_setupComponent : function(cmp) {
			if (CA.Interfaces.Check(cmp, "IBroadcastHandlerComponent")) {
				var component_id = cmp["GetComponentID"]();
				if (typeof (components_to_groups[component_id]) === "undefined") {
					components_to_groups[component_id] = [];
				} else {
					throw new Error("Component has been registered");
				}
			}
		},
		/**
		 * A method that unregisters all group communication for a component 
		 * @function UnregisterAll
		 * @param {Object} cmp The component
		 */
		UnregisterAll : function(cmp) {
			if (CA.Interfaces.Check(cmp, "IBroadcastHandlerComponent")) {
				var component_id = cmp["GetComponentID"]();
				var cmpGroups = components_to_groups[component_id];
				for ( var i = 0; i < cmpGroups.length; i++) {
					var groupName = cmpGroups[i];
					var group = groups[group];
					var cmp_index = group.indexOf(component_id);
					if (cmp_index != -1) {
						group.splice(cmp_index, 1);
					}
					if (group.length === 0) {
						delete groups[groupName];
					}
				}
				if (CA.Components.Get(component_id) === null) {
					delete components_to_groups[component_id];
				}
			}
		},
		/**
		 * A method that unregisters a group communication for a component
		 * 
		 * @function UnregisterForBroadcast
		 * @param {Object} cmp The component
		 * @param {string} group the group
		 */
		UnregisterForBroadcast : function(cmp, group) {
			CA.Interfaces.Ensure(cmp, "IBroadcastHandlerComponent");
			var component_id = cmp["GetComponentID"]();
			var grouplist = components_to_groups[component_id];
			var index = grouplist.indexOf(group);
			if (index != -1) {
				grouplist.splice(index, 1);
				groupl = groups[group];
				var cmpIndex = groupl.indexOf(component_id);
				groupl.splice(cmpIndex, 1);
				if (groupl.length === 0) {
					delete groups[group];
				}
			}
		},
		/**
		 * A method that registers a group communication for a component
		 * @function RegisterForBroadcast
		 * @param {Object} cmp The component
		 * @param {string} group the group
		 */
		RegisterForBroadcast : function(cmp, group) {
			CA.Interfaces.Ensure(cmp, "IBroadcastHandlerComponent");
			var component_id = cmp["GetComponentID"]();
			var grouplist = components_to_groups[component_id];
			if (grouplist.indexOf(group) == -1) {
				grouplist.push(group);
				if (typeof (groups[group]) === "undefined") {
					groups[group] = [];
				}
				groups[group].push(component_id);
			}
		},
		/**
		 * A method that fires an event on a component
		 * additional arguments will be passed on as part of the broadcast
		 * @function BroadcastMessage
		 * @param {string} group The group to broadcast to
		 */
		BroadcastMessage : function(group) {
			if (typeof (groups[group]) !== "undefined") {
				var grouplist = groups[group].slice(0);
				for ( var i = 0; i < grouplist.length; i++) {
					var cmp = CA.Components.Get(grouplist[i]);
					if (cmp) {
						try {
							cmp["OnBroadcast"].apply(cmp, arguments);
						} catch (e) {
						}
					}
				}
			}
		}
	};
})();
